<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { getConfigDetailByKey } from '@/api/config/client'
import { getActiveAdvertList } from '@/api/advert/client'

interface ImageItem {
  imageUrl: string
  linkUrl: string
  width: number
  height: number
  title: string
}

const imgList = ref<ImageItem[]>([])

// 默认图片列表
const defaultImages = [
  { imageUrl: '/images/1.webp', linkUrl: '', title: 'banner1', width: 1080, height: 250 },
  { imageUrl: '/images/2.webp', linkUrl: '', title: 'banner2', width: 1080, height: 250 },
  { imageUrl: '/images/3.webp', linkUrl: '', title: 'banner3', width: 1080, height: 250 }
]

// 计算最大高度
const maxHeight = computed(() => {
  if (imgList.value.length === 0) return '250px'
  const heights = imgList.value.map((item) => item.height).filter((height) => !isNaN(height))
  if (heights.length === 0) return '250px'
  return Math.max(...heights) + 'px'
})

// 新增：处理图片点击事件
const handleImageClick = (linkUrl: string) => {
  if (linkUrl) {
    window.location.href = linkUrl
  }
}

const fetchAdsConfig = async () => {
  try {
    // 先获取配置中的广告位ID
    const res = await getConfigDetailByKey('home-ads')
    if (res.code === 200) {
      // 解析配置中的value字段，它应该是广告位ID
      const positionId = parseInt(res.data.value)

      // 根据广告位ID获取激活的广告列表
      const advertRes = await getActiveAdvertList(positionId)

      if (advertRes.code === 200 && advertRes.data.length > 0) {
        // 遍历广告列表，解析contentJson字段
        const parsedImages = advertRes.data
          .map((item) => {
            try {
              return JSON.parse(item.contentJson)
            } catch (e) {
              console.error('解析contentJson失败:', e)
              return null
            }
          })
          .filter((item) => item && item.imageUrl) // 过滤掉解析失败和没有图片的项

        // 如果解析后的图片列表不为空，则使用解析后的数据，否则使用默认图片
        if (parsedImages.length > 0) {
          imgList.value = parsedImages as ImageItem[]
        } else {
          imgList.value = defaultImages
        }
      } else {
        // 当返回数据为空或请求失败时，使用默认图片
        imgList.value = defaultImages
      }
    } else {
      // 当获取配置失败时，使用默认图片
      imgList.value = defaultImages
    }
  } catch (error) {
    console.error('获取广告配置失败:', error)
    // 如果获取配置失败，使用默认图片
    imgList.value = defaultImages
  }
}

onMounted(() => {
  fetchAdsConfig()
})
</script>

<template>
  <div class="carousel-wrapper">
    <el-carousel :height="maxHeight" arrow="hover">
      <el-carousel-item v-for="(item, index) in imgList" :key="index">
        <el-image
          :src="item.imageUrl"
          :alt="item.title"
          fit="cover"
          class="img-box"
          @click="handleImageClick(item.linkUrl)"
          style="cursor: pointer"
        />
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<style scoped>
.carousel-wrapper {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

/* 让 el-image 填充满轮播项并垂直水平居中 */
.el-carousel__item {
  display: flex;
  justify-content: center;
  align-items: center;
}
.img-box {
  width: 100%;
  height: v-bind(maxHeight);
}

@media (min-width: 768px) {
  .carousel-wrapper {
    padding: 0 20px;
  }
}

@media (min-width: 1024px) {
  .carousel-wrapper {
    padding: 0 24px;
  }
}
</style>
